package sit.mycatalog.web.mbean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

import sit.mycatalog.ejb.sess.CatnodeSess;
import sit.mycatalog.ejb.sess.ItemSess;
import sit.mycatalog.ejb.sess.SysuserSess;
import sit.mycatalog.jpa.Catnode;
import sit.mycatalog.jpa.Item;
import sit.mycatalog.jpa.Sysuser;
import sit.mycatalog.util.ConfigConstant;
import sit.mycatalog.util.SessLookup;
import sit.mycatalog.web.util.AbstractMBean;

public class AdminBean extends AbstractMBean implements Serializable {
	private static final long serialVersionUID = -6654923749672550391L;

	private final String MODE_NEW = "NEW";
	private final String MODE_EDIT = "EDIT";

	private List<Sysuser> sysuserList;
	private List<Item> itemList;
	private List<Catnode> catnodeList;

	private String usrid;
	private String usrname;
	private String usrpwd;
	private String usrnewpwd;
	private String usrconfirmpwd;

	private Integer catid;
	private String catname;
	private String cattype;
	private Integer catparentid;
	private List<SelectItem> optionParent;
	private List<SelectItem> optionCattype;
	private List<SelectItem> optionCatid;

	private String item;
	private String itemdesc;
	private Double itemprice;
	private Double itemheight;
	private Double itemlength;
	private Double itemdepth;
	private Boolean itemhot;
	private Integer itemcatid;
	private String itemimagepath;

	private String usrMode;
	private String itemMode;
	private String catnodeMode;

	// private Boolean disableUsrid;
	private Boolean showChangePwd;

	private Boolean disableItem;
	private Boolean disableCatnode;
	
	private UploadedFile uploadedFile;

	public List<Sysuser> getSysuserList() {
		return sysuserList;
	}

	public void setSysuserList(List<Sysuser> sysuserList) {
		this.sysuserList = sysuserList;
	}

	public List<Item> getItemList() {
		return itemList;
	}

	public void setItemList(List<Item> itemList) {
		this.itemList = itemList;
	}

	public List<Catnode> getCatnodeList() {
		return catnodeList;
	}

	public void setCatnodeList(List<Catnode> catnodeList) {
		this.catnodeList = catnodeList;
	}

	public String getUsrid() {
		return usrid;
	}

	public void setUsrid(String usrid) {
		this.usrid = usrid;
	}

	public String getUsrname() {
		return usrname;
	}

	public void setUsrname(String usrname) {
		this.usrname = usrname;
	}

	public String getUsrpwd() {
		return usrpwd;
	}

	public void setUsrpwd(String usrpwd) {
		this.usrpwd = usrpwd;
	}

	// public Boolean getDisableUsrid() {
	// return disableUsrid;
	// }

	// public void setDisableUsrid(Boolean disableUsrid) {
	// this.disableUsrid = disableUsrid;
	// }

	public Boolean getShowChangePwd() {
		return showChangePwd;
	}

	public void setShowChangePwd(Boolean showChangePwd) {
		this.showChangePwd = showChangePwd;
	}

	public String getUsrnewpwd() {
		return usrnewpwd;
	}

	public void setUsrnewpwd(String usrnewpwd) {
		this.usrnewpwd = usrnewpwd;
	}

	public String getUsrconfirmpwd() {
		return usrconfirmpwd;
	}

	public void setUsrconfirmpwd(String usrconfirmpwd) {
		this.usrconfirmpwd = usrconfirmpwd;
	}

	public String getUsrMode() {
		return usrMode;
	}

	public void setUsrMode(String usrMode) {
		this.usrMode = usrMode;
	}

	public Integer getCatid() {
		return catid;
	}

	public void setCatid(Integer catid) {
		this.catid = catid;
	}

	public String getCatname() {
		return catname;
	}

	public void setCatname(String catname) {
		this.catname = catname;
	}

	public String getCattype() {
		return cattype;
	}

	public void setCattype(String cattype) {
		this.cattype = cattype;
	}

	public Integer getCatparentid() {
		return catparentid;
	}

	public void setCatparentid(Integer catparentid) {
		this.catparentid = catparentid;
	}

	public String getItemMode() {
		return itemMode;
	}

	public void setItemMode(String itemMode) {
		this.itemMode = itemMode;
	}

	public String getCatnodeMode() {
		return catnodeMode;
	}

	public void setCatnodeMode(String catnodeMode) {
		this.catnodeMode = catnodeMode;
	}

	public Boolean getDisableItem() {
		return disableItem;
	}

	public void setDisableItem(Boolean disableItem) {
		this.disableItem = disableItem;
	}

	public Boolean getDisableCatnode() {
		return disableCatnode;
	}

	public void setDisableCatnode(Boolean disableCatnode) {
		this.disableCatnode = disableCatnode;
	}

	public List<SelectItem> getOptionParent() {
		return optionParent;
	}

	public void setOptionParent(List<SelectItem> optionParent) {
		this.optionParent = optionParent;
	}

	public List<SelectItem> getOptionCattype() {
		return optionCattype;
	}

	public void setOptionCattype(List<SelectItem> optionCattype) {
		this.optionCattype = optionCattype;
	}

	public String getItem() {
		return item;
	}

	public void setItem(String item) {
		this.item = item;
	}

	public String getItemdesc() {
		return itemdesc;
	}

	public void setItemdesc(String itemdesc) {
		this.itemdesc = itemdesc;
	}

	public Double getItemprice() {
		return itemprice;
	}

	public void setItemprice(Double itemprice) {
		this.itemprice = itemprice;
	}

	public Boolean getItemhot() {
		return itemhot;
	}

	public void setItemhot(Boolean itemhot) {
		this.itemhot = itemhot;
	}

	public Integer getItemcatid() {
		return itemcatid;
	}

	public void setItemcatid(Integer itemcatid) {
		this.itemcatid = itemcatid;
	}

	public String getItemimagepath() {
		return itemimagepath;
	}

	public void setItemimagepath(String itemimagepath) {
		this.itemimagepath = itemimagepath;
	}

	public List<SelectItem> getOptionCatid() {
		return optionCatid;
	}

	public void setOptionCatid(List<SelectItem> optionCatid) {
		this.optionCatid = optionCatid;
	}
	
	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}	

	public Double getItemheight() {
		return itemheight;
	}

	public void setItemheight(Double itemheight) {
		this.itemheight = itemheight;
	}

	public Double getItemlength() {
		return itemlength;
	}

	public void setItemlength(Double itemlength) {
		this.itemlength = itemlength;
	}

	public Double getItemdepth() {
		return itemdepth;
	}

	public void setItemdepth(Double itemdepth) {
		this.itemdepth = itemdepth;
	}

	@PostConstruct
	public void init() {
		try {
			// disableUsrid = new Boolean(true);
			loadAll();
			
			this.usrMode = MODE_EDIT;
			this.catnodeMode = MODE_EDIT;
			this.itemMode = MODE_EDIT;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	private void loadAll() {
		try {
			SysuserSess sessSysuser = SessLookup.getSysuserSess();
			this.sysuserList = sessSysuser.getAll();

			ItemSess sessItem = SessLookup.getItemSess();
			this.itemList = sessItem.getAll();

			CatnodeSess sessCatnode = SessLookup.getCatnodeSess();
			this.catnodeList = sessCatnode.getAll();
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void selectUser(ActionEvent event) {
		try {
			// System.out.println("Select user :" + usrid);
			SysuserSess sessSysuser = SessLookup.getSysuserSess();
			Sysuser sysuser = sessSysuser.getSysuser(getParameter("usrid"));

			this.usrid = sysuser.getUsrid();
			this.usrname = sysuser.getName();

			LoginBean loginBean = (LoginBean) getSessionAttribute("loginBean");
			if (sysuser.getUsrid().equals(loginBean.getUserid())) {
				this.showChangePwd = new Boolean(true);
			} else {
				this.showChangePwd = new Boolean(false);
			}

			this.usrMode = MODE_EDIT;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void newUser(ActionEvent event) {
		this.usrid = null;
		this.usrname = null;
		this.usrpwd = null;
		this.usrnewpwd = null;
		this.usrconfirmpwd = null;

		// this.disableUsrid = new Boolean(false);
		this.showChangePwd = new Boolean(false);
		this.usrMode = MODE_NEW;
	}

	public void saveUser(ActionEvent event) {
		try {
			// System.out.println("user :" + usrid);
			Sysuser sysuser = new Sysuser();
			sysuser.setUsrid(usrid);
			sysuser.setName(usrname);

			sysuser.setPwd(usrpwd);
			sysuser.setNewpwd(usrnewpwd);
			sysuser.setConfirmpwd(usrconfirmpwd);

			SysuserSess sessSysuser = SessLookup.getSysuserSess();

			if (this.usrMode.equals(MODE_EDIT)) {
				if (sessSysuser.updateSysuser(sysuser)) {
					message("Save Complete");
				} else {
					message("Save Fail");
				}
			} else {
				if (sessSysuser.createSysuser(sysuser)) {
					message("Save Complete");
				} else {
					message("Save Fail");
				}
			}

			this.usrMode = MODE_EDIT;
			this.sysuserList = sessSysuser.getAll();
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void deleteUser(ActionEvent event) {
		try {
			LoginBean loginBean = (LoginBean) getSessionAttribute("loginBean");
			SysuserSess sessSysuser = SessLookup.getSysuserSess();

			if (loginBean.getUserid().equals(usrid)) {
				message("You cannot delete your own id");
			} else {
				if (sessSysuser.deleteUser(usrid)) {
					message("Delete Complete");
					this.usrid = null;
					this.usrname = null;
					this.usrpwd = null;
					this.usrnewpwd = null;
					this.usrconfirmpwd = null;
					// this.disableUsrid = new Boolean(false);
					this.showChangePwd = new Boolean(false);
					this.usrMode = MODE_EDIT;
					this.sysuserList = sessSysuser.getAll();
				} else {
					message("Delete Fail");
				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void clearUser(ActionEvent event) {
		try {
			this.usrid = null;
			this.usrname = null;
			this.usrpwd = null;
			this.usrnewpwd = null;
			this.usrconfirmpwd = null;
			// this.disableUsrid = new Boolean(false);
			this.showChangePwd = new Boolean(false);
			this.usrMode = MODE_EDIT;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void selectCatnode(ActionEvent event) {
		try {
			CatnodeSess sessCatnode = SessLookup.getCatnodeSess();
			Catnode catnode = sessCatnode.getCatnode(Integer.parseInt(getParameter("catid")));

			this.catid = catnode.getCatid();
			this.catname = catnode.getName();
			this.cattype = catnode.getCattype();
			this.catparentid = catnode.getParentid();

			this.catnodeMode = MODE_EDIT;

			loadCattype();
			loadParent(catid);
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	private void loadCattype() {
		this.optionCattype = new ArrayList<SelectItem>();
		this.optionCattype.add(new SelectItem("G", "Group"));
		this.optionCattype.add(new SelectItem("N", "Node"));
	}

	private void loadParent(Integer p_exceptNode) {
		try {
			this.optionParent = new ArrayList<SelectItem>();

			CatnodeSess sessCatnode = SessLookup.getCatnodeSess();
			List<Catnode> lsCatnode = sessCatnode.getAllExcept(p_exceptNode);
			for (int i = 0; i < lsCatnode.size(); i++) {
				Catnode catnode = lsCatnode.get(i);
				this.optionParent.add(new SelectItem(catnode.getCatid().toString(), catnode.getCatid().toString() + ": " + catnode.getName()));
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void newCatnode(ActionEvent event) {
		try {
			this.catid = null;
			this.catname = null;
			this.cattype = "N";
			this.catparentid = new Integer(0);
			loadCattype();
			loadParent(null);
			this.catnodeMode = MODE_NEW;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void saveCatnode(ActionEvent event) {
		try {
			Catnode catnode = new Catnode();
			catnode.setCatid(catid);
			catnode.setCattype(cattype);
			catnode.setName(catname);
			catnode.setParentid(catparentid);

			CatnodeSess sessCatnode = SessLookup.getCatnodeSess();

			if (this.catnodeMode.equals(MODE_EDIT)) {
				if (sessCatnode.updateCatnode(catnode)) {
					message("Save Complete");
				} else {
					message("Save Fail");
				}
			} else {
				if (sessCatnode.createCatnode(catnode)) {
					message("Save Complete");
				} else {
					message("Save Fail");
				}
			}

			this.catnodeMode = MODE_EDIT;
			this.catnodeList = sessCatnode.getAll();
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void deleteCatnode(ActionEvent event) {
		try {
			CatnodeSess sessCatnode = SessLookup.getCatnodeSess();

			if (sessCatnode.deleteCatnode(catid)) {
				message("Delete Complete");
				this.catid = null;
				this.catname = null;
				this.cattype = "N";
				this.catparentid = new Integer(0);
				this.optionCattype = null;
				this.optionParent = null;
				this.catnodeMode = MODE_EDIT;
				this.catnodeList = sessCatnode.getAll();
			} else {
				message("Delete Fail");
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void clearCatnode(ActionEvent event) {
		try {
			this.catid = null;
			this.catname = null;
			this.cattype = "N";
			this.catparentid = new Integer(0);
			this.optionCattype = null;
			this.optionParent = null;
			this.catnodeMode = MODE_EDIT;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void selectItem(ActionEvent event) {
		try {
			ItemSess sessItem = SessLookup.getItemSess();
			Item item = sessItem.getItem(getParameter("item"));

			this.item = item.getItem();
			this.itemdesc = item.getDescription();
			
			if ((item.getHot() != null) && (item.getHot().equals("Y"))) {
				this.itemhot = new Boolean(true);
			} else {
				this.itemhot = new Boolean(false);
			}
			
			this.itemprice = item.getPrice();
			this.itemheight = item.getHeight();
			this.itemlength = item.getLength();
			this.itemdepth = item.getDepth();
			this.itemcatid = item.getCatid();
			this.itemimagepath = item.getImgpath();
			
			loadCatid();
			
			this.itemMode = MODE_EDIT;

		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	private void loadCatid() {
		try {
			this.optionCatid = new ArrayList<SelectItem>();

			CatnodeSess sessCatnode = SessLookup.getCatnodeSess();
			List<Catnode> lsCatnode = sessCatnode.getNodeOnly();

			for (int i = 0; i < lsCatnode.size(); i++) {
				Catnode catnode = lsCatnode.get(i);
				this.optionCatid.add(new SelectItem(catnode.getCatid().toString(), catnode.getCatid().toString() + ": " + catnode.getName()));
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void newItem(ActionEvent event) {
		try {
			this.item = null;
			this.itemdesc = null;
			this.itemhot = new Boolean(false);
			this.itemprice = null;
			this.itemheight = null;
			this.itemlength = null;
			this.itemdepth = null;
			this.itemcatid = null;
			this.itemimagepath = null;
			
			loadCatid();
			this.itemMode = MODE_NEW;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void saveItem(ActionEvent event) {
		try {
			Item item = new Item();
			item.setItem(this.item);
			item.setDescription(this.itemdesc);
			item.setPrice(this.itemprice);
			item.setHeight(this.itemheight);
			item.setLength(this.itemlength);
			item.setDepth(this.itemdepth);
			item.setCatid(this.itemcatid);
			
			
			if((this.itemhot != null) && (this.itemhot.booleanValue())) {
				item.setHot("Y");
			} else {
				item.setHot(null);
			}
			
			ItemSess sessItem = SessLookup.getItemSess();
			
			if(this.itemMode.equals(MODE_EDIT)) {
				if(sessItem.updateItem(item)) {
					message("Save Complete");
				} else {
					message("Save Fail");
				}
			} else {
				if(sessItem.createItem(item)) {
					message("Save Complete");
				} else {
					message("Save Fail");
				}
			}

			this.itemMode = MODE_EDIT;
			this.itemList = sessItem.getAll();

		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void deleteItem(ActionEvent event) {
		try {
			ItemSess sessItem = SessLookup.getItemSess();
			if(sessItem.deletItem(item)) {
			message("Delete Complete");
			this.item = null;
			this.itemdesc = null;
			this.itemhot = new Boolean(false);
			this.itemprice = null;
			this.itemheight = null;
			this.itemlength = null;
			this.itemdepth = null;
			this.itemcatid = null;
			this.itemimagepath = null;
			
			this.optionCatid = null;
			this.itemMode = MODE_EDIT;
			this.itemList = sessItem.getAll();
		} else {
			message("Delete Fail");
		}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void clearItem(ActionEvent event) {
		try {
			this.item = null;
			this.itemdesc = null;
			this.itemhot = new Boolean(false);
			this.itemprice = null;
			this.itemheight = null;
			this.itemlength = null;
			this.itemdepth = null;
			this.itemcatid = null;
			this.itemimagepath = null;
			
			optionCatid = null;
			this.itemMode = MODE_EDIT;
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
	
	public String uploadFile() {
		try {
//		System.out.println(item);
			
//		String fileName = FilenameUtils.getName(uploadedFile.getName());
		String extension = FilenameUtils.getExtension(uploadedFile.getName());
//		String contentType = uploadedFile.getContentType();
		byte[] bytes = uploadedFile.getBytes();
		
		ItemSess sessItem = SessLookup.getItemSess();
		
		String strFileName = item + "." + extension.toLowerCase();
		
		File fileImage = new File(ConfigConstant.ITEM_IMAGE_PATH + strFileName);
		
		if(fileImage.exists()) {
			fileImage.delete();
		}
		
		FileOutputStream fos = new FileOutputStream(fileImage);
		fos.write(bytes);
		fos.flush();
		
		sessItem.updateImagePath(item, strFileName);
		
		this.itemimagepath = strFileName;
		this.itemList = sessItem.getAll();
		
//		System.out.print(fileName);

//		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(String.format("File '%s' of type '%s' successfully uploaded!", fileName, contentType)));
		} catch(Exception e) {
			e.printStackTrace(System.out);
		}
		
		return "OK";
	}
}
